package com.taotao.st3.base.enumhub.enumat;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.NullifyingDeserializer;
import com.taotao.st3.base.enumhub.CodeTextEnum;
import com.taotao.st3.base.enumhub.EnumHub;
import com.taotao.st3.base.enumhub.EnumId;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class EnumAtDeSerializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    private String fieldName;
    private EnumField enumAt;

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String  s = jsonParser.readValueAs(String.class);
        // 转换为需要的 枚举类型

        return null;
    }


    private String getDisplayName(Class<? extends CodeTextEnum> enumClass, Object value) {
        try {

            // 获取枚举的最新版本
            EnumId enumId = enumClass.getAnnotation(EnumId.class);
            if (null != enumId) {
                enumClass = EnumHub.getEnumClass(enumId.value());
            }

            //反射调用枚举的values方法
            CodeTextEnum[] values = (CodeTextEnum[]) enumClass.getMethod("values").invoke(new Object(), new Object[]{});
            if (null == values || 0 == values.length) {
                return null;
            }

            for (CodeTextEnum e : values) {
                if (Objects.equals(e.getCode(), value)) {
                    return e.getText();
                }
            }

        } catch (Exception e) {
            log.error("", e);
        }

        return null;
    }



    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            //为空直接跳过
            return new NullifyingDeserializer();
        }


        EnumField enumAt = beanProperty.getAnnotation(EnumField.class);
        if (null == enumAt) {
            return deserializationContext.findContextualValueDeserializer(beanProperty.getType(), beanProperty);
        }

        return new EnumAtDeSerializer(beanProperty.getName(), enumAt);
    }
}